﻿using System;
using System.Collections.Generic;
using System.Text;

namespace HCService.Tools
{
	public class MsgCacheTools
	{   //For Seek
		public int Position { get; protected set; } = 0;

		public byte[] Buffer { get; protected set; }


		public MsgCacheTools(int msgLength)
		{
			//消息字符串至少为 2 * sizeof(Int32)
			if (msgLength > 0)
			{
				Buffer = new byte[msgLength];
			}
			else
			{
				throw new Exception("SocketMsgCreater Constructor Invail Length");
			}
			this.Clear();
		}

		public void Clear()
		{
			Position = 0;
		}

		protected void ReSize(int length)
		{
			if (length > Buffer.Length)
			{
				var newlen = Buffer.Length * 2 >= length ? Buffer.Length * 2 : length;
				byte[] temp = new byte[newlen];
				Array.Copy(Buffer, temp, Buffer.Length);
				Buffer = temp;
			}
		}

		public void Write(byte[] bytes)
		{

			var len = bytes.Length;
			ReSize(Position + len);
			Array.Copy(bytes, 0, Buffer, Position, len);
			Position += len;
		}


		public void Write(string str)
		{
			byte[] strByte = System.Text.Encoding.UTF8.GetBytes(str);
			this.Write(strByte);
		}

		public void Write(int integer)
		{
			byte[] intByte = BitConverter.GetBytes(integer);
			this.Write(intByte);
		}

	}
}
